import requests
from .log_utils import logger


class HttpClient:
    @staticmethod
    def send_request(method, url, headers=None, data=None, is_json=True):
        """统一的HTTP请求处理函数

        Args:
            method (str): 请求方法 (get, post, put, delete)
            url (str): 请求URL
            headers (dict, optional): 请求头
            data (dict, optional): 请求数据
            is_json (bool, optional): 是否以JSON格式发送数据

        Returns:
            dict: 响应数据
        """
        try:
            headers = headers or {}
            data = data or {}
            method = method.lower()

            if method == "get":
                response = requests.get(url, headers=headers, params=data)
            elif method == "post":
                response = requests.post(
                    url, headers=headers, json=data if is_json else data
                )
            elif method == "put":
                response = requests.put(
                    url, headers=headers, json=data if is_json else data
                )
            elif method == "delete":
                response = requests.delete(url, headers=headers)
            else:
                logger.error(f"不支持的请求方法: {method}")
                return {}

            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            logger.error(f"请求 {url} 失败: {e}")
            return {}
        except ValueError:
            logger.error(f"请求 {url} 的响应不是有效的 JSON 格式。")
            return {}

    @staticmethod
    def assert_response(response, assert_config):
        """统一的响应断言处理函数
        Args:
            response: 响应对象
            assert_config (dict): 断言配置
        """
        if "status_code" not in assert_config:
            logger.error("断言配置中必须包含 status_code 字段。")
            return

        expected_status_code = assert_config.get("status_code")
        if response.status_code != expected_status_code:
            response.failure(
                f"状态码断言失败: 期望状态码 {expected_status_code}，实际状态码 {response.status_code}"
            )
            logger.error(
                f"状态码断言失败: 期望状态码 {expected_status_code}，实际状态码 {response.status_code}"
            )
        else:
            response.success()
            logger.info(f"状态码断言成功~~")

        try:
            response_json = response.json()
            for key, expected in assert_config.items():
                if key != "status_code":
                    actual = response_json.get(key)
                    if actual != expected:
                        response.failure(
                            f"响应内容 {key} 断言失败: 期望 {expected} ，实际为 {actual}"
                        )
                        logger.error(
                            f"响应内容 {key} 断言失败: 期望 {expected} ，实际为 {actual}"
                        )
                    else:
                        response.success()
                        logger.info(f"响应内容 {key} 断言成功~~")
        except ValueError:
            response.failure("响应内容不是有效的 JSON 格式，无法进行断言检查。")
            logger.error("响应内容不是有效的 JSON 格式，无法进行断言检查。")
